const Controller = require('egg').Controller;

class MidjourneyController extends Controller {
    /**
     * Create a new Midjourney task (imagine)
     */
    async create() {
        const { ctx, service } = this;
        const params = ctx.request.body;

        // Validate required parameters
        if (!params.prompt) {
            this.ctx.error(500, '提示词不能为空')
            return;
        }
        if (!params.conversationId) {
            this.ctx.error(500, '会话窗口不存在')
        }

        // Call service to create Midjourney task
        const result = await service.mj.create(params);
        this.ctx.success(result)
    }

    /**
     * Fetch task status and result
     */
    async fetch() {
        const { ctx, service } = this;
        const params = ctx.query;

        // Validate required parameters
        if (!params.taskId) {
            this.ctx.error(500, '任务ID不存在')
            return;
        }

        // Call service to fetch task status
        const result = await service.mj.fetch(params);
        this.ctx.success(result)
    }

    /**
     * Perform action on a Midjourney result (upscale, variation, reroll)
     */
    async action() {
        const { ctx, service } = this;
        const params = ctx.request.body;

        // Validate required parameters
        if (!params.taskId || !params.customId) {
            this.ctx.error(500, '任务ID不存在')
            return;
        }

        // Call service to perform action
        const result = await service.mj.action(params);
        this.ctx.success(result)
    }

    /**
     * Get available Midjourney models or change model settings
     */
    async model() {
        const { ctx, service } = this;
        const params = ctx.request.body;
        if (!params.maskBase64) {
            this.ctx.error(500, '重绘内容为空')
        }
        if (!params.prompt) {
            this.ctx.error(500, '提示词为空')
        }
        if (!params.taskId) {
            this.ctx.error(500, '任务ID为空')
        }
        // Call service to get model information
        const result = await service.mj.model(params);
        this.ctx.success(result)
        ctx.body = result;
    }
}

module.exports = MidjourneyController;
